<?php

namespace app\admin\controller\account;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * 财务中心
 *
 * @icon fa fa-acount
 */
class Account extends Backend
{

    protected $searchFields = 'username,tradenumber';

    /**
     * @var \app\admin\model\Acount
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Account');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
           
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
			$params = $this->request->post("row/a");
			if ($params) {
				$result = false;
				Db::startTrans();
				
				try {
					$user_model = model('User');
					$user = $user_model->where('username', $params['username'])->find();
					if($user)
					{
						$params['u_id'] = $user['id'];
						$params['tradenumber'] = date('YmdHis').mt_rand(1000,9999);
						$params['trade_before'] = $user['score'];
						$params['trade_point'] = $user['keywordsprice']*$params['money'];
						$params['trade_after'] = $user['score'] = $user['score']+$params['trade_point'];
						$params['tradetime'] = time();
						$params['remarks'] = '管理员代充：消费充值';
					}

					$result = $this->model->validate('Account.add')->save($params);
					if ($result === false) {
                        exception($this->model->getError());
                    } else {
						$user->save();
					}
					Db::commit();
				} catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
				$this->success();
			}
			$this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}
